package com.apps.stoolkit;

import com.apps.smodule.PengDB.service.SpiderDB;
import com.apps.sworld.sToolkit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 我自己实现的单机锁
 */
@Slf4j
@Component
public class SpiderLockToolkit implements sToolkit {

    private static SpiderDB<String,Boolean> spiderDB;

    //默认尝试时间 秒为单位
    private static long tryTime=5;
    //每次尝试的时间间隔,毫秒为单位
    private static long tryTimeSpace=10;
    //锁自动释放的时间
    private static long releaseTime=6;

    @Override
    public void onLoad()
    {

    }

    @Autowired
    public void setSpiderDB(SpiderDB<String,Boolean> db)
    {
        spiderDB=db;
    }
    /**
     * 获取锁
     * @param key
     * @return
     */
    public static  boolean Lock(String key)
    {
        if(null == spiderDB.get(key) ) {
            spiderDB.set(key,true,releaseTime);
            return true;
        }
        return false;
    }
    //按默认设置尝试获取锁
    public static  boolean tryLock(String key)  {

        return tryLock(key,tryTime,releaseTime,TimeUnit.SECONDS);
    }
    //按传入参数尝试获取锁
    public static synchronized boolean tryLock(String key,Long try_time,Long release_time,TimeUnit unit) {
        try {
            //简单的获取锁,
            if (null == try_time && null == release_time && null == unit) {
                if (null == spiderDB.get(key)) {
                    spiderDB.set(key, true, releaseTime);
                    return true;
                }
                return false;
            }
            //尝试获取锁
            for (long i = 0; i < unit.toMillis(try_time); i += tryTimeSpace) {
                if (null == spiderDB.get(key)) {
                    spiderDB.set(key, true, unit.toMillis(release_time));
                    return true;
                }
                Thread.sleep(tryTimeSpace);
            }

        }catch (Exception e)
        {
            log.error(e.getMessage());
        }

        return false;
    }

    public static void unlock(String key)
    {
        spiderDB.del(key);
    }
}
